import 'dart:io';
import 'package:dio/dio.dart';
import 'package:mi_mang_flutter/model/public/entity_factory.dart';
import 'package:mi_mang_flutter/model/public/file_model.dart';
import 'package:mi_mang_flutter/network/client.dart';
import 'package:mi_mang_flutter/network/extra_keys.dart';
import 'package:mi_mang_flutter/network/response_data.dart';

import 'package:path/path.dart' as path;

const String _API_ALI_OSS_SINGLE = '/api/media/upload';

/// 单个文件上传
///
/// [file] 文件流对象
/// [storType] 资源存储方式(1.本地存储,2.七牛,3.阿里)
Future<ResponseData<FileModel>> upload(
  File file, {
  int storeType = 2,
  ProgressCallback? onSendProgress,
}) async {
  var response = await client.formDataPost(
    _API_ALI_OSS_SINGLE,
    data: {
      "file": MultipartFile.fromFileSync(
        file.path,
        filename: path.basename(file.path),
      ),
      "storeType": storeType
    },
    options: Options(extra: {
      ExtraKeys.NEED_TOKEN: true,
    }),
    onSendProgress: onSendProgress,
  );
  return ResponseData<FileModel>(
    code: response.code,
    msg: response.msg,
    data: EntityFactory.generateOBJ(response.data),
  );
}

/// 批量上传
///
/// [file] 文件流对象
/// [storType] 资源存储方式(1.本地存储,2.七牛,3.阿里)
Future<ResponseData> batchUpload(
  List<File> files, {
  int storeType = 2,
  ProgressCallback? onSendProgress,
}) async {
  var formData = files.map(
    (file) => MapEntry(
      "file",
      MultipartFile.fromFileSync(
        file.path,
        filename: path.basename(file.path),
      ),
    ),
  );
  return client.formDataPost(
    _API_ALI_OSS_SINGLE,
    data: {
      "files": formData,
      "storeType": storeType,
    },
    options: Options(extra: {
      ExtraKeys.NEED_TOKEN: true,
      ExtraKeys.NEED_LOADING: true,
      ExtraKeys.NEED_LOADING_MSG: "正在上传...",
    }),
    onSendProgress: onSendProgress,
  );
}
